package edu.nus.mtech.sem1.ca.data;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import edu.nus.mtech.sem1.ca.utils.IOUtils;
import edu.nus.mtech.sem1.ca.utils.Logger;
import edu.nus.mtech.sem1.ca.utils.TelephonyConstants;

public class ConfigurationUtils {

	/**
	 * Loads configuration from the file into a Property 
	 */
	private static Properties applicationConfiguration=null;
	
	public static Properties loadConfiguration() {

		if (applicationConfiguration!=null){
			return applicationConfiguration;
		}
		InputStream inputStream=null;
		try {
			applicationConfiguration=new Properties();
			//TODO fix this. Use resourcestream instead of fileinputstream
			//inputStream=TelephonyApplicationConfiguration.class.getResourceAsStream(TelephonyConstants.TELEPHONY_APPLICATION_PROPERTIES_FILE_NAME);
			inputStream=new FileInputStream(TelephonyConstants.TELEPHONY_APPLICATION_PROPERTIES_FILE_NAME);
			applicationConfiguration.load(inputStream);
			
			Logger.log("Application Configuration is......"+applicationConfiguration);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.err.println(TelephonyConstants.ERR_COULD_NOT_LOAD_APP_CONFIG+ e.getMessage());
			System.exit(1);
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println(TelephonyConstants.ERR_COULD_NOT_LOAD_APP_CONFIG+ e.getMessage());
			System.exit(1);
		}catch (Exception e) {
			e.printStackTrace();
			System.err.println(TelephonyConstants.ERR_COULD_NOT_LOAD_APP_CONFIG+ e.getMessage());
			System.exit(1);
		}
		finally{
			//To avoid the too many files open. Not that it matters in a small application like this but still... you never know
			IOUtils.closeQuietly(inputStream);
		}
		
		return applicationConfiguration;
	}
	
}
